#pragma once
#include <iostream>
#include <unordered_map>
#include <cstring>

#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
using namespace std;

// 单个用户
class User
{
public:
    User(const std::string &ip, const uint16_t &port)
        : _ip(ip), _port(port) {}
    ~User() {}

    string ip() { return _ip; }
    uint16_t port() { return _port; }

private:
    std::string _ip;
    uint16_t _port;
};

// 在线用户
class onlineUsers
{
public:
    onlineUsers() {}
    ~onlineUsers() {}

    // 增加用户
    void addUser(const std::string &ip, const uint16_t &port)
    {
        string id = ip + to_string(port);
        _users.insert(make_pair(id, User(ip, port)));
    }

    // 删除用户
    void delUser(const std::string &ip, const uint16_t &port)
    {
        string id = ip + to_string(port);
        _users.erase(id);
    }

    // 判断用户是否存在
    bool ifUserOnline(const std::string &ip, const uint16_t &port)
    {
        string id = ip + to_string(port);
        return _users.find(id) == _users.end() ? false : true;
    }

    void broadCastMessage(int sockfd, const std::string &ip, const uint16_t &port, const string &message)
    {
        for (auto &user : _users)
        {
            struct sockaddr_in client;
            memset(&client, 0, sizeof(client));

            client.sin_family = AF_INET;
            client.sin_port = htons(user.second.port());
            string s = ip + '[' + to_string(port) + ']';
            s += message;
            sendto(sockfd, s.c_str(), s.size(), 0, (sockaddr *)&client, sizeof(client));
        }
    }

private:
    unordered_map<string, User> _users;
};